/*
 * Copyright (c) 2010, Nikolaus Moll
 * All rights reserved.
 */
package net.gradecalculator.plugin.core.stux.internal;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

import net.gradecalculator.plugin.loader.exceptions.PluginException;

@XmlRootElement(namespace = "http://gradecalculator.net/", name="university")
@XmlType(
 propOrder = { "name", "countryCode" } 
) 

public class XmlUniversity {
	private String name;
	private String countryCode;
	
	@XmlElement(name = "name")
	public String getName() {
		return name;
	}
	public void setName(final String name) {
		this.name = name;
	}
	
	@XmlElement(name = "countrycode")
	public String getCountryCode() {
		return countryCode;
	}
	public void setCountryCode(final String countryCode) {
		this.countryCode = countryCode;
	}

	public static XmlUniversity createFromXML(final String filename) {
		XmlUniversity result = null;
		Reader xmlinput = null;
		try {
			final JAXBContext context = JAXBContext.newInstance(XmlUniversity.class);
			final Unmarshaller unmarshaller = context.createUnmarshaller();
			xmlinput = new FileReader(filename);
			result = (XmlUniversity) unmarshaller.unmarshal(xmlinput);
		} catch (final JAXBException jaxbException) {
			throw new PluginException("Error reading university xml " + filename, jaxbException);
		} catch (final Exception e) {
			throw new PluginException("Error reading university xml " + filename, e);
		} finally {
			try {
				if (xmlinput != null) {
					xmlinput.close();
				}
			} catch (final IOException e) {
				throw new PluginException("Error closing university xml", e);
			}
		}
		return result;
	}

	public void saveXML(final String filename) {
		Writer xmloutput = null;
		try {
			final JAXBContext context = JAXBContext.newInstance(XmlUniversity.class);
			final Marshaller marshaller = context.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
			xmloutput = new FileWriter(filename);
			marshaller.marshal(this, xmloutput);
			xmloutput.flush();
		} catch (final JAXBException jaxbException) {
			throw new PluginException("Error writing university xml", jaxbException);
		} catch (final Exception e) {
			throw new PluginException("Error saving university xml", e);
		} finally {
			try {
				if (xmloutput != null) {
					xmloutput.close();
				}
			} catch (final Exception e) {
				throw new PluginException("Error closing university xml", e);
			}
		}
	}
}
